package sunwul.mall.gateway.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;
import sunwul.mall.commonbase.constant.AuthConstants;
import sunwul.mall.commonbase.constant.BusinessStatusEnum;
import sunwul.mall.commonbase.constant.HttpConstants;
import sunwul.mall.commonbase.model.Result;
import sunwul.mall.gateway.config.WhiteUrlConfig;

/**
 * @author sunwul
 * @date 2024/12/6 14:08
 * @description 全局认证过滤器
 * 前后端约定好令牌存放的位置, 请求头的Authorization bearer token
 */
@Component
@Slf4j
public class AuthFilter implements GlobalFilter, Ordered {

    @Autowired
    WhiteUrlConfig whiteUrlConfig;

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    /**
     * 校验token
     * 1. 获取请求路径
     * 2. 判断请求路径是否可以放行
     *      - 放行: 不做处理
     *      - 不放行: 需要对其进行身份认证
     * 3.
     * @param exchange
     * @param chain
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取请求对象
        ServerHttpRequest request = exchange.getRequest();
        // 获取请求路径
        String path = request.getPath().toString();
        log.info("AuthFilter - path=" + path);
        // 判断当前请求路径是否可以放行, 是否存在白名单中
        if (whiteUrlConfig.getAllowUrls().contains(path)) {
            // 存在白名单中, 直接放行
            return chain.filter(exchange);
        }
        // 非白名单请求路径, 校验身份信息
        String authorizationValue = request.getHeaders().getFirst(AuthConstants.AUTHORIZATION);
        log.info("AuthFilter - authorization=" + authorizationValue);
        if (StringUtils.hasText(authorizationValue)) {
            String tokenValue = authorizationValue.replaceFirst(AuthConstants.BEARER, "");
            log.info("isexist-" + (StringUtils.hasText(tokenValue) || stringRedisTemplate.hasKey(AuthConstants.LOGIN_TOKEN_PREFIX + tokenValue)));
            // token非空且存在于redis, 放行
            if (StringUtils.hasText(tokenValue) ||
                    stringRedisTemplate.hasKey(AuthConstants.LOGIN_TOKEN_PREFIX + tokenValue)) {
                return chain.filter(exchange);
            }
        }
        ServerHttpResponse response = exchange.getResponse();
        response.getHeaders().set(HttpConstants.CONTENT_TYPE, HttpConstants.APPLICATION_JSON);
        Result<Object> result = Result.fail(BusinessStatusEnum.UN_AUTHORIZATION);

        ObjectMapper mapper = new ObjectMapper();
        byte[] bytes = new byte[0];
        try {
            bytes = mapper.writeValueAsBytes(result);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        DataBuffer dataBuffer = response.bufferFactory().wrap(bytes);
        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return -5;
    }
}
